package com.dongdongshop.aop;

import com.alibaba.fastjson.JSONObject;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
@Aspect //将当前类定义为切面类
public class LogAspect {

    private Logger logger = LoggerFactory.getLogger("LogAspect");

    //定义切点表达式
    @Pointcut("execution(public * com.dongdongshop.service.*.*(..)) || @annotation(com.dongdongshop.anontaion.Log)")
    public void aopLog(){}

    //前置通知:被拦截的方法调用之前打印
    @Before("aopLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable{

        //获取被拦截参数
        Object[] args = joinPoint.getArgs();

        //获取被拦截方法名
        Signature signature = joinPoint.getSignature();

        logger.info("进入方法: {}, 参数为: {}", signature, args);
    }

    //返回后通知:被拦截的方法调用之后打印
    @AfterReturning(value = "aopLog()", returning = "obj")
    public void doAfter(Object obj){
        logger.info("方法调用成功, 获取返回值为:{}", JSONObject.toJSONString(obj));
    }
}
